import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { Prisma, User } from '@prisma/client';
import { PrismaService } from '../prisma.service';
import { returnFail } from '../common/response';
import { CODE } from '../common/base';
import { nameVerify, passwordVerify } from 'src/common/util/verify';
import { jwtConstants } from './constants';
import { TJwtPayload } from './typing';

@Injectable()
export class AuthService {
  constructor(
    private prisma: PrismaService,
    private readonly jwtService: JwtService,

  ) { }

  async create(userReq: User) {
    try {
      const isHave = await this.prisma.user.findUnique({
        where: { username: userReq.username}
      })

      if (isHave) {
        return { msg: '用户已存在，请更改用户名', data: null, sql: true}
      }
      // 校验用户名和密码
      if(!passwordVerify(userReq.password) || !nameVerify(userReq.username)) {
        return { msg:'注册校验不通过！', data: '', sql: true };
      }
      const user: any = {
        username: userReq.username,
        password: userReq.password,
        avatar: userReq.avatar || 'https://5b0988e595225.cdn.sohucs.com/images/20190701/d2e5518b44c643a1b52d39853cc33af5.jpeg',
        role: 'user',
      }
      const res = await this.prisma.user.create({ data: user })
      const payload: TJwtPayload = {userId: res.userId, password: res.password};
      const token = await this.jwtService.signAsync(payload, {secret: jwtConstants.secret})

      return { data: { user: res, token: token }, msg: '注册用户成功' }
    } catch (error) {
      // 执行sql失败
      return { msg: error, data: null, sql: true }
    }
  }

  async login(userReq: User) {
    try {
      const user = await this.prisma.user.findUnique({
        where: { username: userReq.username, password: userReq.password }
      })

      if (!user) {
        return { msg: '用户密码或用户名错误', data: null, sql: true}
      }

      const payload: TJwtPayload = {userId: user.userId, password: user.password};
      const token = await this.jwtService.signAsync(payload, {secret: jwtConstants.secret})

      return { data: { user: user, token: token }, msg: '用户登录成功' }
    } catch (error) {
      // 执行sql失败
      return { msg: error, data: null, sql: true }
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} auth`;
  }

  update(id: number, updateAuthDto: UpdateAuthDto) {
    return `This action updates a #${id} auth`;
  }

  remove(id: number) {
    return `This action removes a #${id} auth`;
  }
}
